package com.sychip.fhc.app.drawer.screen.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.PlainTooltip
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.RangeSlider
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fhc.view.FhcBottomSheet
import com.fhc.view.FhcComoBox
import com.fhc.view.FhcVerticalSlider
import com.fhc.view.KeyLabel
import com.fhc.view.rememberFhcBottomSheetVisibleState
import com.fhc.view.rememberFhcComoBoxState
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.lib.base.FhcTopAppBar
import com.sychip.fhc.lib.base.isDouble
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ComponentsScreen(modifier: Modifier = Modifier,
                     onNavigationClick: () -> Unit ={},viewModel: ComponentsViewModel = hiltViewModel(),
                     snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }) {
    val dialogState = rememberDialogState()
    val tooltipState = rememberTooltipState()
    val scope = rememberCoroutineScope()

    Scaffold(
        topBar = {
            FhcTopAppBar(
                title =  R.string.app_name,
                navigationIcon = {
                    IconButton(onClick = onNavigationClick) {
                        Icon(Icons.Filled.Menu, stringResource(id = R.string.open_drawer))
                    }
                },
                actions = {
                    IconButton(onClick = {
                        scope.launch { }
                    }) {
                        Icon(Icons.Filled.Refresh, null)
                    }
                    IconButton(onClick = {
                        scope.launch { }
                    }) {
                        Icon(Icons.Filled.Close, null)
                    }
                },
            )
        },
    ) { innerPadding ->
//        val modifier = Modifier
//        .fillMaxSize().padding(top = innerPadding.calculateTopPadding())
        Box (modifier = Modifier
            .fillMaxSize()
            .padding(paddingValues = innerPadding)){
            Column (
                verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
                horizontalAlignment = Alignment.CenterHorizontally,
            ){

                val coroutineScope: CoroutineScope = rememberCoroutineScope()
                var sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
                var visibleState = rememberFhcBottomSheetVisibleState()
                OutlinedButton(onClick = {
                    visibleState.value = true
                }) {
                    Text("Fhc BottomSheet")
                }
                FhcBottomSheet(title = "ssssss",sheetState=sheetState, visibleState = visibleState,coroutineScope=coroutineScope, onActionYes = {
                    true
                }){
                    RangeSetting()
                }

//            SimpleBottomSheetScaffold(modifier)

                CustomModalBottomSheetDemo()

                DialogWithImage(state = dialogState)
                OutlinedButton(onClick = { scope.launch { dialogState.show() } }) {
                    Text("Display DialogWithImage")
                }

                TooltipBox(
                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                    tooltip = { PlainTooltip { Text("Add to list") } },
                    state = tooltipState
                ) {
                    Icon(imageVector = Icons.Filled.AddCircle, contentDescription = "Localized Description")
                }
                OutlinedButton(onClick = { scope.launch { tooltipState.show() } }) {
                    Text("Display tooltip")
                }

                ModalNavigationDrawerSample()



            }

        }

    }

}


data class DataRange(
    var decimals: String = "0",
    var minRange: String = "0",
    var maxRange: String = "999",
){

}


@Composable
fun checkDecimals( states :DataRange): String{
    if(!states.decimals.isDouble(canEmpty = false)){

        return stringResource(R.string.err_invalid_value)
    }else if(states.decimals.toDouble() > 99 || states.decimals.toDouble() < 0){

        return stringResource(R.string.err_number_range,0, 3)
    }
    return ""
}


@Preview
@Composable
fun RangeSetting( ){

    val mItemsList = remember {
        mutableStateOf(
            listOf(
                KeyLabel("","--"),
                KeyLabel("Android","Android"),
                KeyLabel("iOS","iOS"),
                KeyLabel("Angular","Angular"),
                KeyLabel("Python","Python"),
                KeyLabel("Electron","Electron"),
                KeyLabel("111","1111"),
                KeyLabel("222","2222"),
                KeyLabel("333","3331234567890qwertyuiopasdfghjkl;'zxccvcbvnvbmnbmhj yter 4tt yj5y 6Q twtwt333333333333333"),
                KeyLabel("444","444444444444444444444\n4444444444444444444444"),
                KeyLabel("555","12\n33\n33\n33\n33"),
                KeyLabel("666","666\n66"),
                KeyLabel("777","7\n7"),
            )
        )
    }
    var states by remember {mutableStateOf(DataRange())}
    var errInfo by remember { mutableStateOf("") }
//    var errorInfo by remember { mutableStateOf("This is an errora\naaaa\naaaaaaaaaa\naaaaaaaaaa\naaaaaaaaaaaaa\naaaaaaaa\naaaaaaaaaaaaaa") }
    val paddingLeft = 10.dp
    val paddingRow = 18.dp

    var selectedKeyLabel = rememberFhcComoBoxState()
    selectedKeyLabel.value = mItemsList.value[6]
    Row(modifier= Modifier.wrapContentSize().padding(top = paddingRow, bottom = paddingRow, start = paddingLeft, end = paddingLeft)) {

        Column(verticalArrangement = Arrangement.spacedBy(18.dp)){
            if(!errInfo.isEmpty()) {
                Row(modifier = Modifier.wrapContentSize()) {
                    Icon(Icons.Filled.Error, null, tint = Color.Red, modifier = Modifier.size(30.dp))
                    Text(errInfo, color = Color.Red, modifier = Modifier.fillMaxWidth().heightIn(min = 30.dp).wrapContentSize(align = Alignment.CenterStart))
                }
            }

            FhcComoBox(
                modifier = Modifier.padding(0.dp),
                label = { Text("Please ---") },
                selectedKeyLabel = selectedKeyLabel,
                colors =  OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = colorScheme.primary,
                    unfocusedBorderColor =  colorScheme.primary
                ),
                items = mItemsList
            )
            OutlinedButton(onClick = {
                selectedKeyLabel.value = mItemsList.value[mItemsList.value.size - 1]
            }) {
                Text("FhcComoBox Value")
            }
            OutlinedButton(onClick = {
                selectedKeyLabel.value =null
            }) {
                Text("FhcComoBox null")
            }
            RadioGroupSample()

            CheckBoxSample()

            SliderExamples()

            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = states.decimals,
                label = { Text(text = "Decimals") },
                onValueChange = {it->
                    if (it.length <= 3) states = states.copy(decimals = it)
                },
                placeholder = {Text("Decimals")},
                singleLine = true,
                isError = !errInfo.isEmpty(),
                supportingText = {
                    errInfo = checkDecimals(states)
                    if (!errInfo.isEmpty()) {
                        Text(errInfo)
                    }
                },
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Decimal
                ),
            )

            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value =  states.minRange,
                onValueChange = {
                    states = states.copy(minRange = it)
                },
                placeholder = {Text("minRange")},
                singleLine = true,
                label = { Text(text = "minRange") },
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Number
                ),
            )

            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value =  states.maxRange,
                onValueChange = {
                    states = states.copy(maxRange = it)
                },
                placeholder = {Text("maxRange")},
                singleLine = true,
                label = { Text(text = "maxRange") },
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Number
                ),
            )
        }
    }
}


@Composable
private fun RadioGroupSample() {
    /* Here Create List for radioButton */
    val radioOptions = listOf("Red ", "Blue ", "Black ")
    /* Here Create State of radioButton */
    var selectedOption by remember { mutableStateOf("") }

    Card(
        colors =  CardDefaults.cardColors(containerColor = Color.Transparent),
        modifier = Modifier
            .padding(vertical = 10.dp)
            .fillMaxWidth(),
        elevation =CardDefaults.elevatedCardElevation(defaultElevation =0.dp ) ,
        shape = RoundedCornerShape(8.dp),
        border = BorderStroke(2.dp, colorScheme.primary.copy(0.5f)),
    ) {

        Column{
            Text(
                modifier = Modifier.padding(start = 16.dp,top = 16.dp),
                text = "Radio Group:",
                style = MaterialTheme.typography.titleSmall
            )
            Row(Modifier.fillMaxWidth().padding(start = 16.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Start
            ) {
                radioOptions.forEach { text ->
                    Row(
                        Modifier.weight(1f).padding(bottom = 4.dp)
                        .clickable(
                            onClick = {
                                selectedOption = text
                            }
                        ), verticalAlignment = Alignment.CenterVertically
                        , horizontalArrangement = Arrangement.Start
                    ) {
                        RadioButton(
                            modifier =   Modifier,
                            selected = (text == selectedOption),
                            onClick = {
                                selectedOption = text
                            },
                            colors = RadioButtonDefaults.colors(selectedColor = colorScheme.primary)
                        )
                        Text(
                            text = text,
                            textAlign = TextAlign.Center,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }
        }
    }
}


@Composable
fun CheckBoxSample() {
    /* Here Create State of checkbox */
    val mItemsList = remember {
        mutableStateOf(
            listOf(
                Profession("Android"),
                Profession("iOS"),
                Profession("Angular"),
                Profession("Python"),
                Profession("Electron"),
                Profession("")
            )
        )
    }


    Card(
        colors =  CardDefaults.cardColors(containerColor = Color.Transparent),
        modifier = Modifier
            .padding(vertical = 10.dp)
            .fillMaxWidth(),
        elevation =CardDefaults.elevatedCardElevation(defaultElevation =0.dp ) ,
        shape = RoundedCornerShape(8.dp),
        border = BorderStroke(2.dp, colorScheme.primary.copy(0.5f)),
    ) {
        Column(Modifier.background(colorScheme.background).fillMaxWidth()) {
            Column{
                Text(
                    modifier = Modifier.padding(start = 16.dp,top = 16.dp),
                    text = "CheckBox:",
                    style = MaterialTheme.typography.titleSmall
                )
                Row(Modifier.fillMaxWidth().padding(start = 16.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Start
                ) {
                    mItemsList.value.forEachIndexed { index, items ->
                        if(index <3){
                            Row(
                                modifier = Modifier.weight(1f).padding(bottom = 4.dp)
                                    .clickable(
                                        onClick = {
                                            mItemsList.value[index].value.value = !mItemsList.value[index].value.value
                                        }
                                    ),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Start
                            ) {
                                Checkbox(
                                    checked = mItemsList.value[index].value.value,
                                    onCheckedChange = { mItemsList.value[index].value.value = it },
                                    enabled = true,
                                    colors = CheckboxDefaults.colors(
                                        checkedColor = colorScheme.secondary,
                                        uncheckedColor = Color.DarkGray,
                                        checkmarkColor = Color.White
                                    )
                                )
                                Text(
                                    text = items.text,
                                    style = MaterialTheme.typography.bodySmall
                                )
                            }
                        }
                    }
                }
                Row(Modifier.fillMaxWidth().padding(start = 16.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Start
                ) {
                    mItemsList.value.forEachIndexed { index, items ->
                        if(index >=3){
                            Row(
                                modifier = Modifier.weight(1f).padding(bottom = 4.dp)
                                    .clickable(
                                        onClick = {
                                            mItemsList.value[index].value.value = !mItemsList.value[index].value.value
                                        }
                                    ),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Start
                            ) {
                                if(!items.text.isEmpty()) {
                                    Checkbox(
                                        checked = mItemsList.value[index].value.value,
                                        onCheckedChange = { mItemsList.value[index].value.value = it },
                                        enabled = true,
                                        colors = CheckboxDefaults.colors(
                                            checkedColor = colorScheme.secondary,
                                            uncheckedColor = Color.DarkGray,
                                            checkmarkColor = Color.White
                                        )
                                    )
                                    Text(
                                        text = items.text,
                                        style = MaterialTheme.typography.bodySmall
                                    )
                                }
                            }
                        }
                    }
                }
        }
    }
    }
}


@Composable
fun SliderExamples() {
    val headerStyle = MaterialTheme.typography.titleSmall
    val spaceHeight = 24.dp
    var sliderPosition by remember { mutableIntStateOf(8) }
    Card(
        colors =  CardDefaults.cardColors(containerColor = Color.Transparent),
        modifier = Modifier
            .padding(vertical = 10.dp)
            .fillMaxWidth(),
        elevation =CardDefaults.elevatedCardElevation(defaultElevation =0.dp ) ,
        shape = RoundedCornerShape(8.dp),
        border = BorderStroke(2.dp, colorScheme.primary.copy(0.5f)),
    ) {
        Row(modifier = Modifier.background(Color.Gray)){
            Spacer(Modifier.requiredWidth(spaceHeight))
            FhcVerticalSlider(modifier = Modifier.size(40.dp,400.dp), progress = sliderPosition,
                onValueChange = {
                    sliderPosition = it
                })
            Spacer(Modifier.requiredWidth(spaceHeight))
            Column(Modifier.fillMaxHeight().background(Color.Gray).weight(1f)) {
                Column(Modifier.padding(20.dp)) {
                    Text(text = "Continuous Slider", style = headerStyle)
                    SliderSample()
                    Spacer(Modifier.requiredHeight(spaceHeight))
                    Text(text = "Discrete Slider with custom color", style = headerStyle)
                    StepsSliderSample()
                    Spacer(Modifier.requiredHeight(spaceHeight))
                    Text(text = "Range Continuous Slider", style = headerStyle)
                    RangeSliderSample()
                    Spacer(Modifier.requiredHeight(spaceHeight))
                    Text(text = "Range Discrete Slider", style = headerStyle)
                    StepRangeSliderSample()
                }
            }
        }
    }
}

@Composable
fun SliderSample() {
    var sliderPosition by remember { mutableFloatStateOf(0f) }
    Text(text = "Slider value =  $sliderPosition",style = MaterialTheme.typography.bodySmall)
    Slider(value = sliderPosition, onValueChange = { sliderPosition = it })
}

@Composable
fun StepsSliderSample() {
    var sliderPosition by remember { mutableFloatStateOf(10f) }
    Text(text = "Slider value =  $sliderPosition",style = MaterialTheme.typography.bodySmall)
    Slider(
        value = sliderPosition,
        onValueChange = { sliderPosition = it },
        valueRange = 0f..100f,
        onValueChangeFinished = {
            // some business logic update with the state you hold
        },
        steps = 5,
        colors = SliderDefaults.colors(
            thumbColor = colorScheme.primary,
            activeTrackColor = colorScheme.secondary
        )
    )
}

@Composable
fun RangeSliderSample() {
    var sliderPosition by remember { mutableStateOf(10f..100f) }
    Text(
        text = "From range  ${sliderPosition.start}  to  ${sliderPosition.endInclusive}",
        style = MaterialTheme.typography.bodySmall
    )
    RangeSlider(
        value = sliderPosition,
        onValueChange = { sliderPosition = it },
        valueRange = 0f..100f,
        onValueChangeFinished = {  },
    )
}

@Composable
fun StepRangeSliderSample() {
    var sliderPosition by remember { mutableStateOf(40f..100f) }
    Text(
        text = "From range  ${sliderPosition.start}  to  ${sliderPosition.endInclusive}",
       style = MaterialTheme.typography.bodySmall
    )
    RangeSlider(
        value = sliderPosition,
        onValueChange = { sliderPosition = it },
        valueRange = 0f..100f,
        steps = 5,
        onValueChangeFinished = {  },
        colors = SliderDefaults.colors(
            thumbColor = colorScheme.primary,
            activeTrackColor = colorScheme.secondary
        )
    )
}